const axios = require('axios')
const db = require('../db/index')
// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 导入配置文件
const config = require('../config');
const { log } = require('console');



exports.login = async (req, res) => {
  const { code } = req.body;

  if (!code) {
    return res.status(400).json({ success: false, message: '缺少 code 参数' });
  }

  try {
    // 请求微信服务器获取 openid 和 session_key
    const { data } = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
      params: {
        appid: 'wx3036dc5d51baca90',
        secret: 'c2b0812dcefcec6d26714040a5c7b72b',
        js_code: code,
        grant_type: 'authorization_code',
      },
    });

    if (data.errcode) {
      return res.status(400).json({ success: false, message: data.errmsg });
    }

    const { openid, session_key } = data;

    if (openid) {
      // 生成 JWT token，包含 openid 和 session_key
      const token = jwt.sign({ openid, session_key }, config.jwtSecretKey, { expiresIn: '10h' });
      res.json({ success: true, openid, session_key, token: 'Bearer ' + token });//返回值
    }
    else {
      res.status(400).json({ success: false, message: '获取 openid 失败' });
    }
  } catch (err) {
    console.error('微信 API 请求失败:', err);
    res.status(500).json({ success: false, message: '服务器错误' });
  }


  /* // 检查用户是否已经存在
  db.query('SELECT * FROM users WHERE openid = ?', [openid], (err, results) => {
    if (err) {
      return res.status(500).json({ success: false, message: '数据库查询失败' });
    }

    let user = results[0];
    if (!user) {
      // 用户不存在，创建新用户
      db.query('INSERT INTO users (openid, session_key) VALUES (?, ?)', [openid, session_key], (err, results) => {
        if (err) {
          return res.status(500).json({ success: false, message: '数据库插入失败' });
        }

        user = {
          id: results.insertId,
          openid,
          session_key,
        };
      });
    }
    // 生成JWT token
    const token = jwt.sign({ user: user.id }, config.jwtSecretKey, { expiresIn: '10h' });

    // 返回用户信息
    res.json({
      success: true,
      token: 'Bearer ' + token,
      userInfo: {
        openid: user.openid,
        session_key: user.session_key,
        id: user.id,
      },
    });
  });
} catch (error) {
  console.error(error);
  res.status(500).json({ success: false, message: '请求微信接口失败' });
}  */
}

exports.saveUserInfo = (req, res) => {
  const { openid, session_key, nickName, avatarUrl } = req.body;

  // 插入用户信息到数据库
  const query = `INSERT INTO users (openid, session_key, nickName, avatarUrl)
                 VALUES (?, ?, ?, ?)
                 ON DUPLICATE KEY UPDATE nickName = VALUES(nickName), avatarUrl = VALUES(avatarUrl)`;

  db.query(query, [openid, session_key, nickName, avatarUrl], (err, results) => {
    if (err) {

      console.error('保存用户信息失败:', err);
      return res.status(500).json({ success: false, message: '保存失败' });
    }

    res.json({ success: true, message: '用户信息保存成功' });
  });
}

exports.roomMessage = (req, res) => {
  //res.send('ok')
  const query = 'select * from rooms';

  db.query(query, (err, results) => {
    if (err) {

      console.error('房间信息获取失败:', err);
      return res.status(500).json({ success: false, message: '保存失败' });
    }
    res.json({ success: true, message: '房间信息获取成功', data: results });
  })

}


exports.getImage = (req, res) => {
  const roomId = req.params.roomId;
  const sql = 'SELECT image_url FROM room_images WHERE room_id = ?';

  db.query(sql, [roomId], (err, results) => {
    if (err) {
      return res.status(500).send('Database error');
    }
    res.status(200).json({ success: true, message: '房间照片获取成功', data: results });
  });
}

exports.getMessageImage = (req, res) => {
  const roomId = req.params.roomId;
  const sql = 'SELECT image_url FROM rooms_messageimg WHERE room_id = ?';

  db.query(sql, [roomId], (err, results) => {
    if (err) {
      return res.status(500).send('Database error');
    }
    res.status(200).json({ success: true, message: '房间照片获取成功', data: results });
  });
}

exports.getRoomName = (req, res) => {
  const roomId = req.params.roomId;
  const sql = 'SELECT room_name,price FROM rooms WHERE room_id = ?';

  db.query(sql, [roomId], (err, results) => {
    if (err) {
      return res.status(500).send('Database error');
    }
    res.status(200).json({ success: true, message: '房间名字获取成功', data: results });
  });
}


exports.orderMessage = (req, res) => {
  const sql = `SELECT * FROM orders WHERE payment_status='paid' AND order_status='confirmed'`;
  db.query(sql, (err, results) => {
    if (err) {
      return res.status(500).send('Database error');
    }
    res.status(200).json({ success: true, message: '订单获取成功', data: results });
  });
}

exports.usedRoom = (req, res) => {
  const { status, room_id } = req.params;
  console.log('房间状态', status, room_id);

  const sql = `UPDATE rooms SET status =? WHERE room_id = ?`;
  const sql1 = 'UPDATE rooms SET status =? ';
  if (room_id) {
    db.query(sql, [status, room_id], (err, results) => {
      if (err) {
        console.log(err);
        return res.status(500).json({ message: '更改房间状态失败' })
      }
      res.json({ success: true, message: '更改房间状态成功', data: results });
    })
  } else {
    db.query(sql1, status, (err, results) => {
      if (err) {
        console.log(err);
        return res.status(500).json({ message: '更改房间状态失败' })
      }
      res.json({ success: true, message: '更改房间状态成功', data: results });
    })
  }
}

exports.completedOrder = (req, res) => {
  const { order_status, order_id } = req.body;
  console.log(order_status, order_id)
  const query = `UPDATE orders SET order_status=? WHERE order_id = ? AND payment_status = 'paid'`;
  db.query(query, [order_status, order_id], (err, results) => {
    if (err) {
      return res.status(500).json({ message: '更新失败' }, err);
    }
    if (results.affectedRows === 0) {
      return res.status(404).json({ message: '该订单未找到' });
    }
    res.json({ success: true, message: '修改订单状态成功', data: results });
  });
};



exports.getReviews = (req, res) => {
  const sql = 'SELECT * FROM reviews';
  db.query(sql, (err, results) => {
    if (err) {
      return res.status(500).send('Database error');
    }
    res.status(200).json({ success: true, message: '评价获取成功', data: results });
  });
}

exports.getReviewImg = (req, res) => {
  const order_id = req.body.order_id
  console.log('qqq', order_id)
  const sql = `select * from reviews_img where order_id=?`
  db.query(sql, order_id, (err, results) => {
    if (err) {
      return res.status(500).json({ message: '评价表图片获取失败' })
    }
    res.json({ success: true, message: '评价表图片获取成功', data: results });
  })
}

exports.getuserinfo = (req, res) => {
  const user_id = req.params.user_id;
  console.log(user_id);
  const query = `select avatarUrl,nickName,user_id FROM users where user_id=?`

  db.query(query, user_id, (err, results) => {
    if (err) {
      console.error('查询错误:', err);
      return res.status(500).json({ message: '查询失败' });
    }
    res.json({ success: true, message: '用户信息获取成功', data: results });  // 返回所有有效的优惠券
  })

}

exports.uplike = (req, res) => {
  const {order_id} = req.body
  const sql ='select likes from reviews where order_id = ?'
  db.query(sql,order_id,(err,results)=>{
    if (err) {
      console.error('查询错误:', err);
      return res.status(500).json({ message: '查询失败' });
    }

    if (results.length === 0) {
      return res.status(404).json({ message: '没有找到该订单的评论' });
    }

    let likes= results[0].likes
    likes += 1;
    console.log(likes, order_id);
    const query = `UPDATE reviews SET likes=? WHERE order_id = ?`
    db.query(query, [likes, order_id], (err, results) => {
      if (err) {
        console.error('查询错误:', err);
        return res.status(500).json({ message: 'like修改失败' });
      }

    })
  })
}

exports.InsteComment = (req, res) => {
  const { order_id, comment } = req.body
  console.log(order_id, comment)
  const sql = `INSERT INTO comments (order_id,comment)VALUES (?,?);`
  db.query(sql, [order_id, comment], (err, results) => {
    if (err) {
      return res.status(500).json({ message: '评价表新增失败' })
    }
    res.json({ success: true, message: '评价表新增成功', data: results });
  })
}

exports.selComment = (req, res) => {
  const order_id = req.params.order_id
  const query = `select * FROM comments where order_id=?`
  db.query(query, order_id, (err, results) => {
    if (err) {
      console.error('查询错误:', err);
      return res.status(500).json({ message: '查询失败' });
    }
    res.json({ success: true, message: '评论信息获取成功', data: results });  // 返回所有有效的优惠券
  })

}